#include "groupchatwindow.h"
#include "ui_groupchatwindow.h"
#include <QFileDialog>
#include <QFileInfo>
#include <QMessageBox>
#include "chatwindow.h"
GroupChatWindow::GroupChatWindow(ChatWindow *parentChatWindow,QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::GroupChatWindow)
    ,groupSocket(new QTcpSocket(this))
{
    ui->setupUi(this);
    this->setWindowTitle("群聊界面");

    connect(ui->pushButton_message,&QPushButton::clicked,this,&GroupChatWindow::sendmessage);
    connect(ui->pushButton_file,&QPushButton::clicked,this,&GroupChatWindow::sendFile);
    connect(groupSocket,&QTcpSocket::readyRead,this,&GroupChatWindow::handleMessageReceived);

    userName = parentChatWindow->getUserName();

    groupSocket->connectToHost("192.168.1.220",8989);
    if(groupSocket->waitForConnected(3000))
    {
        qDebug() << "群聊连接成功";
    }
    else
    {
        qDebug() << "群聊连接失败";
    }

}

GroupChatWindow::~GroupChatWindow()
{
    delete ui;
}
//发送消息
void GroupChatWindow::sendmessage()
{
    QString message = ui->lineEdit->text();
    if(message.isEmpty())
    {
        QMessageBox::warning(this,tr("警告"),tr("请输入消息"));
        return;
    }

    ui->textEdit_chatMessage->append(tr("%1：%2").arg(userName).arg(message));
    ui->lineEdit->clear();
    groupSocket->write(message.toUtf8());
}

void GroupChatWindow::sendFile()
{
    QString fileName = QFileDialog::getOpenFileName(this,tr("选择文件"),"",tr("所有文件(*)"));
    if(fileName.isEmpty())
    {
        return;
    }

    QFileInfo fileInfo(fileName);
    QString fileNameStr = fileInfo.fileName();
    qint64 fileSize = fileInfo.size();

    QByteArray fileNameData = "FILE:";
    fileNameData.append(fileNameStr);
    fileNameData.append(":");
    fileNameData.append(QString::number(fileSize).toUtf8());

    groupSocket->write(fileNameData);
    if(groupSocket->waitForBytesWritten(3000))
    {
        QFile file(fileName);
        if(file.open(QIODevice::ReadOnly))
        {
            while (!file.atEnd())
            {
                QByteArray block = file.read(1024);
                groupSocket->write(block);
                groupSocket->waitForBytesWritten(3000);

            }
            file.close();
            qDebug() << "文件发送成功";

            ui->textEdit_chatMessage->append(tr("%1：发送了文件 %2").arg(userName).arg(fileName));
        }
    }

}

void GroupChatWindow::handleMessageReceived()
{
    QByteArray data = groupSocket->readAll();
    QString message = QString::fromUtf8(data);
    ui->textEdit_chatMessage->append(message);
}

void GroupChatWindow::on_pushButton_close_clicked()
{
    ChatWindow *chatWindow = new ChatWindow(this);
    chatWindow->show();
    this->hide();
}

